﻿var express = require('express')
var router = express.Router()
var T = require('./utils.js')
var config = require('../config')

var P = {
  logoutRequest: function (req, res) {
    T.ajax({
      url: '/logout.json',
      method: 'post',
      headers: {
        'xticket': req.session.ticket || '',
        'X-Requested-With': 'XMLHttpRequest'
      },
      host: config.ssoHost,
      json: true,
      success: function (result) {
        result = T.tryEval(result) || {}

        console.log('logout', result)

        var data = result.value
        if (result.success) {
          req.session.userInfo = null
          req.session.ticket = null

          var loginUrl = T.getLoginUrl(req, true)
          res.json({ success: true, value: loginUrl })
        } else {
          res.json({ success: false, errorMsg: '退出超时，请稍候' })
        }
      }
    }, res)
  },
  requestUserInfo: function (req, res) {
    var userInfo = req.session.userInfo || {}

    res.json({ success: true, value: userInfo })
    return

    T.ajax({
      url: '/user/queryUserPriviledges',
      method: 'post',
      headers: {
        'xticket': req.session.ticket || '',
        'X-Requested-With': 'XMLHttpRequest'
      },
      data: { userId: userInfo.userId },
      host: config.priviledgesHost,
      json: true,
      success: function (result) {
        result = T.tryEval(result) || {}

        console.log('userInfo', result)

        var data = result.value
        userInfo.privilegeMap = data || {}
        res.json({ success: true, value: userInfo })
      }
    }, res)
  }
}

router.all('*', function (req, res, next) {
  var method = req.params[0]
  var reqData = req.body || {}
  var url = req.originalUrl.replace(/^\/ajax/i, '')
  const ajaxParam = {
    url: url,
    method: 'post',
    data: reqData,
    json: true,
    headers: {
      'userToken': req.session.userInfo && req.session.userInfo.userToken || ''
    },
    success: function (result) {
      res.send(result)
    }
  }

  // const contentTypeUrl = ['/rateTable/create']
  // if (contentTypeUrl.indexOf(url) >= 0) {
  //     ajaxParam.contentType = 'multipart/form-data'
  // }

  // 数据模拟
  if (process.env.NODE_ENV !== 'production' && reqData.mock === true) {
    var mock = require('./mock')
    mock(ajaxParam)
    return
  }

  if (url.indexOf('/getUserInfo') > -1) {
    P.requestUserInfo(req, res)
    return
  }

  if (url.indexOf('/logoutRequest') > -1) {
    P.logoutRequest(req, res)
    return
  }

  if (ajaxParam.data.mock !== undefined) {
    delete ajaxParam.data.mock
  }

  if (url.includes('smartclaim')) {
    ajaxParam.host = config.smartclaim
  }

  console.log('ajaxParam', ajaxParam)

  T.ajax(ajaxParam, res)
})

module.exports = router
